﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using MSDNWebcast.Models;
using System;

namespace MSDNWebcast.Service
{
    /// <summary>
    /// 下载服务
    /// </summary>
    public class DownloadService
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly object syncRoot = new object();

        /// <summary>
        /// 下载列表
        /// </summary>
        private readonly List<KeyValuePair<CourseFile, Downloader>> downloaderList = new List<KeyValuePair<CourseFile, Downloader>>();

        /// <summary>
        /// 初始化服务
        /// </summary>
        public DownloadService()
        {
            //限制同时进行下载的数量
            ServicePointManager.DefaultConnectionLimit = 5;
        }

        /// <summary>
        /// 下载课程
        /// </summary>
        public void DownloadCourse(CourseFile courseFile)
        {
            lock (syncRoot)
            {
                var downloader = this.GetDownloader(courseFile);
                if (downloader != null)
                {
                    if (downloader.State == DownloadState.Pause
                        || downloader.State == DownloadState.Error
                        || downloader.State == DownloadState.Canceled)
                    {
                        downloader.Resume();
                        BeginDownloadCourse();
                    }
                }
                else
                {
                    downloader = new Downloader(courseFile.TempFilePath, courseFile.Url);
                    this.downloaderList.Add(new KeyValuePair<CourseFile, Downloader>(courseFile, downloader));
                    OnCourseFileBeginDownloaded(courseFile);
                    downloader.PropertyChanged += delegate
                                                      {
                                                          BeginDownloadCourse();
                                                          if (downloader.State == DownloadState.Finished &&
                                                              !courseFile.CanOpen)
                                                          {
                                                              courseFile.UnZip();
                                                          }
                                                      };
                    BeginDownloadCourse();
                }
            }
        }

        /// <summary>
        /// 开始下载课程
        /// </summary>
        private void BeginDownloadCourse()
        {
            int downloadCount = 0;
            foreach (KeyValuePair<CourseFile, Downloader> keyValuePair in downloaderList)
            {
                if (keyValuePair.Value.State != DownloadState.WaitToDownload &&
                    keyValuePair.Value.State != DownloadState.Downloading)
                    continue;
                if (keyValuePair.Value.State == DownloadState.WaitToDownload)
                {
                    keyValuePair.Value.ProcessAsync();
                }
                downloadCount++;
                if (downloadCount >= 5)
                    break;
            }
        }

        /// <summary>
        /// 下载列表
        /// </summary>
        public List<KeyValuePair<CourseFile, Downloader>> DownloadList
        {
            get { return downloaderList; }
        }

        /// <summary>
        /// 获取下载
        /// </summary>
        /// <param name="courseFile"></param>
        /// <returns></returns>
        internal Downloader GetDownloader(CourseFile courseFile)
        {
            foreach (var keyValuePair in downloaderList)
            {
                if (keyValuePair.Key == courseFile)
                    return keyValuePair.Value;
            }
            return null;
        }

        /// <summary>
        /// 课程开始下载
        /// </summary>
        public event EventHandler<CourseFileBeginDownloadedEventArgs> CourseFileBeginDownloaded;

        private void OnCourseFileBeginDownloaded(CourseFile courseFile)
        {
            if (this.CourseFileBeginDownloaded != null)
                CourseFileBeginDownloaded(this, new CourseFileBeginDownloadedEventArgs { CourseFile = courseFile });
        }
    }

    /// <summary>
    /// 课程开始下载参数
    /// </summary>
    public class CourseFileBeginDownloadedEventArgs : EventArgs
    {
        public CourseFile CourseFile { get; set; }
    }
}